/*
 * FileViewActivity.java
 * classes : com.ruint.lib.mediachooser.activity.FileViewActivity
 * @author ruint
 * V 1.0.0
 * Create at 2014-12-5 下午3:20:16
 */
package com.ruint.lib.mediachooser.activity;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.app.FragmentTabHost;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;

import com.ruint.core.app.BaseActivity;
import com.ruint.core.utils.ui.ToastUtils;
import com.ruint.core.view.dialog.CustomProgressDialog;
import com.ruint.corelib.R;
import com.ruint.lib.mediachooser.core.MediaChooser;
import com.ruint.lib.mediachooser.core.MediaChooserConstants;
import com.ruint.lib.mediachooser.fragment.FileImageFragment;
import com.ruint.lib.mediachooser.fragment.FileImageFragment.OnImageSelectedListener;
import com.ruint.lib.mediachooser.fragment.FileVideoFragment;
import com.ruint.lib.mediachooser.fragment.FileVideoFragment.OnVideoSelectedListener;

/**
 * com.ruint.lib.mediachooser.activity.FileViewActivity
 * 
 * @author ruint <br/>
 *         create at 2014-12-5 下午3:20:16
 */
public class FileViewActivity extends BaseActivity implements OnImageSelectedListener, OnVideoSelectedListener,
    OnClickListener, OnTabChangeListener {

  private FragmentTabHost mTabHost;
  private TextView headerBarTitle;
  private ImageView headerBarCamera;
  private ImageView headerBarBack;
  private ImageView headerBarDone;

  private static Uri fileUri;
  private final Handler handler = new Handler();

  @Override
  protected int getLayoutResID() {
    return R.layout.activity_view_media_chooser;
  }

  @Override
  protected void pre4Create(Bundle savedInstanceState) {
    setSwipeBack(SWIPE_BACK_ENABLE);
    setSwipeBackOrientation(LEFT);
  }

  @Override
  protected void findViews() {
    headerBarTitle = findView(headerBarTitle, R.id.header_title);
    headerBarCamera = findView(headerBarCamera, R.id.header_img_carema);
    headerBarBack = findView(headerBarBack, R.id.header_back_arrow);
    headerBarDone = findView(headerBarDone, R.id.header_submit);
    mTabHost = findView(mTabHost, android.R.id.tabhost);
  }

  @Override
  protected void handleRelevancy() {
    mTabHost.setup(this, getSupportFragmentManager(), R.id.real_tab_content);
    headerBarBack.setOnClickListener(this);
    headerBarCamera.setOnClickListener(this);
    headerBarDone.setOnClickListener(this);
    if (!MediaChooserConstants.showCameraVideo) {
      headerBarCamera.setVisibility(View.GONE);
    }
  }

  @Override
  protected void onLoadingData() {
    if (getIntent() != null && (getIntent().getBooleanExtra("isFromBucket", false))) {

      if (getIntent().getBooleanExtra("image", false)) {
        headerBarTitle.setText(getResources().getString(R.string.image));
        setHeaderBarCameraBackground(getResources().getDrawable(R.drawable.selector_camera_button));

        headerBarCamera.setTag(getResources().getString(R.string.image));

        Bundle bundle = new Bundle();
        bundle.putString("name", getIntent().getStringExtra("name"));
        mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator(getResources().getString(R.string.image) + "     "),
            FileImageFragment.class, bundle);

      } else {
        headerBarTitle.setText(getResources().getString(R.string.video));
        setHeaderBarCameraBackground(getResources().getDrawable(R.drawable.selector_video_button));
        headerBarCamera.setTag(getResources().getString(R.string.video));

        Bundle bundle = new Bundle();
        bundle.putString("name", getIntent().getStringExtra("name"));
        mTabHost.addTab(mTabHost.newTabSpec("tab2").setIndicator(getResources().getString(R.string.video) + "      "),
            FileVideoFragment.class, bundle);
      }
    } else {

      if (MediaChooserConstants.showVideo) {
        mTabHost.addTab(mTabHost.newTabSpec("tab2").setIndicator(getResources().getString(R.string.video) + "      "),
            FileVideoFragment.class, null);
      }

      if (MediaChooserConstants.showImage) {
        headerBarTitle.setText(getResources().getString(R.string.image));
        setHeaderBarCameraBackground(getResources().getDrawable(R.drawable.selector_camera_button));
        headerBarCamera.setTag(getResources().getString(R.string.image));

        mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator(getResources().getString(R.string.image) + "      "),
            FileImageFragment.class, null);
      }

      if (MediaChooserConstants.showVideo) {
        headerBarTitle.setText(getResources().getString(R.string.video));
        setHeaderBarCameraBackground(getResources().getDrawable(R.drawable.selector_video_button));
        headerBarCamera.setTag(getResources().getString(R.string.video));
      }
    }
    initTabs();
  }

  private void initTabs() {
    for (int i = 0; i < mTabHost.getTabWidget().getChildCount(); i++) {

      TextView textView = (TextView) mTabHost.getTabWidget().getChildAt(i).findViewById(android.R.id.title);
      if (textView.getLayoutParams() instanceof RelativeLayout.LayoutParams) {

        RelativeLayout.LayoutParams params = (android.widget.RelativeLayout.LayoutParams) textView.getLayoutParams();
        params.addRule(RelativeLayout.CENTER_HORIZONTAL);
        params.addRule(RelativeLayout.CENTER_VERTICAL);
        params.height = RelativeLayout.LayoutParams.MATCH_PARENT;
        params.width = RelativeLayout.LayoutParams.WRAP_CONTENT;
        mTabHost.getTabWidget().getChildAt(i).findViewById(android.R.id.title).setLayoutParams(params);

      } else if (textView.getLayoutParams() instanceof LinearLayout.LayoutParams) {
        LinearLayout.LayoutParams params = (android.widget.LinearLayout.LayoutParams) textView.getLayoutParams();
        params.gravity = Gravity.CENTER;
        mTabHost.getTabWidget().getChildAt(i).findViewById(android.R.id.title).setLayoutParams(params);
      }

    }
  }

  /** Create a file Uri for saving an image or video */
  private Uri getOutputMediaFileUri(int type) {
    return Uri.fromFile(getOutputMediaFile(type));
  }

  /** Create a File for saving an image or video */
  @SuppressLint("SimpleDateFormat")
  private static File getOutputMediaFile(int type) {

    File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
        MediaChooserConstants.folderName);
    if (!mediaStorageDir.exists()) {
      if (!mediaStorageDir.mkdirs()) {
        return null;
      }
    }

    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    File mediaFile;
    if (type == MediaChooserConstants.MEDIA_TYPE_IMAGE) {
      mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
    } else if (type == MediaChooserConstants.MEDIA_TYPE_VIDEO) {
      mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_" + timeStamp + ".mp4");
    } else {
      return null;
    }

    return mediaFile;
  }

  @SuppressLint("NewApi")
  @SuppressWarnings("deprecation")
  private void setHeaderBarCameraBackground(Drawable drawable) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
      headerBarCamera.setBackgroundDrawable(drawable);
    } else {
      headerBarCamera.setBackground(drawable);
    }
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == MediaChooserConstants.CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {
      if (resultCode == RESULT_OK) {

        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, fileUri));
        final CustomProgressDialog dialog = new CustomProgressDialog(thisInstance);
        dialog.show();
        handler.postDelayed(new Runnable() {
          @Override
          public void run() {
            // Do something after 5000ms
            String fileUriString = fileUri.toString().replaceFirst("file:///", "/").trim();
            FileVideoFragment videoFragment = (FileVideoFragment) getSupportFragmentManager().findFragmentByTag("tab2");
            //
            if (videoFragment == null) {
              FileVideoFragment newVideoFragment = FileVideoFragment.newInstance();
              newVideoFragment.addItem(fileUriString);
            } else {
              videoFragment.addItem(fileUriString);
            }
            dialog.cancel();
          }
        }, 5000);

      } else if (resultCode == RESULT_CANCELED) {
        // User cancelled the video capture
      } else {
        // Video capture failed, advise user
      }
    } else if (requestCode == MediaChooserConstants.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
      if (resultCode == RESULT_OK) {

        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, fileUri));

        final CustomProgressDialog dialog = new CustomProgressDialog(thisInstance);
        dialog.show();
        handler.postDelayed(new Runnable() {
          @Override
          public void run() {
            // Do something after 5000ms
            String fileUriString = fileUri.toString().replaceFirst("file:///", "/").trim();
            FileImageFragment imageFragment = (FileImageFragment) getSupportFragmentManager().findFragmentByTag("tab1");
            if (imageFragment == null) {
              FileImageFragment newImageFragment = FileImageFragment.newInstance();
              newImageFragment.addItem(fileUriString);
            } else {
              imageFragment.addItem(fileUriString);
            }
            dialog.cancel();
          }
        }, 5000);
      }
    }
  }

  @Override
  public void onVideoSelected(int count) {
    if (count != 0) {
      ((TextView) mTabHost.getTabWidget().getChildAt(0).findViewById(android.R.id.title)).setText(getResources()
          .getString(R.string.videos_tab) + "  " + count);

    } else {
      ((TextView) mTabHost.getTabWidget().getChildAt(0).findViewById(android.R.id.title)).setText(getResources()
          .getString(R.string.video));
    }
  }

  @Override
  public void onImageSelected(int count) {
    if (mTabHost.getTabWidget().getChildAt(1) != null) {
      if (count != 0) {
        ((TextView) mTabHost.getTabWidget().getChildAt(1).findViewById(android.R.id.title)).setText(getResources()
            .getString(R.string.images_tab) + "  " + count);

      } else {
        ((TextView) mTabHost.getTabWidget().getChildAt(1).findViewById(android.R.id.title)).setText(getResources()
            .getString(R.string.image));
      }
    } else {
      if (count != 0) {
        ((TextView) mTabHost.getTabWidget().getChildAt(0).findViewById(android.R.id.title)).setText(getResources()
            .getString(R.string.images_tab) + "  " + count);

      } else {
        ((TextView) mTabHost.getTabWidget().getChildAt(0).findViewById(android.R.id.title)).setText(getResources()
            .getString(R.string.image));
      }
    }
  }

  @Override
  public void onClick(View view) {

    if (view == headerBarCamera) {

      if (view.getTag().toString().equals(getResources().getString(R.string.video))) {
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        fileUri = getOutputMediaFileUri(MediaChooserConstants.MEDIA_TYPE_VIDEO);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

        // start the image capture Intent
        startActivityForResult(intent, MediaChooserConstants.CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);

      } else {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        fileUri = getOutputMediaFileUri(MediaChooserConstants.MEDIA_TYPE_IMAGE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

        // start the image capture Intent
        startActivityForResult(intent, MediaChooserConstants.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
      }
    } else if (view == headerBarDone) {

      FileImageFragment imageFragment = (FileImageFragment) getSupportFragmentManager().findFragmentByTag("tab1");
      FileVideoFragment videoFragment = (FileVideoFragment) getSupportFragmentManager().findFragmentByTag("tab2");

      if (videoFragment != null || imageFragment != null) {
        if (videoFragment != null) {
          if (videoFragment.getSelectedVideoList() != null && videoFragment.getSelectedVideoList().size() > 0) {
            Intent videoIntent = new Intent();
            videoIntent.setAction(MediaChooser.VIDEO_SELECTED_ACTION_FROM_MEDIA_CHOOSER);
            videoIntent.putStringArrayListExtra(MediaChooserConstants.MEDIA_SELECTED_LIST,
                videoFragment.getSelectedVideoList());
            sendBroadcast(videoIntent);
          }
        }

        if (imageFragment != null) {
          if (imageFragment.getSelectedImageList() != null && imageFragment.getSelectedImageList().size() > 0) {
            Intent imageIntent = new Intent();
            imageIntent.setAction(MediaChooser.IMAGE_SELECTED_ACTION_FROM_MEDIA_CHOOSER);
            imageIntent.putStringArrayListExtra(MediaChooserConstants.MEDIA_SELECTED_LIST,
                imageFragment.getSelectedImageList());
            sendBroadcast(imageIntent);
          }
        }
        finish();
      } else {
        ToastUtils.showToast(thisInstance, "Nothing selected.");
      }

    } else if (view == headerBarBack) {
      finish();
    }
  }

  @Override
  public void onTabChanged(String tabId) {
    FileImageFragment imageFragment = (FileImageFragment) getSupportFragmentManager().findFragmentByTag("tab1");
    FileVideoFragment videoFragment = (FileVideoFragment) getSupportFragmentManager().findFragmentByTag("tab2");
    ;

    if (tabId.equalsIgnoreCase("tab1")) {

      headerBarTitle.setText(getResources().getString(R.string.image));
      setHeaderBarCameraBackground(getResources().getDrawable(R.drawable.selector_camera_button));
      headerBarCamera.setTag(getResources().getString(R.string.image));

      if (imageFragment != null) {

        if (videoFragment != null) {
          getSupportFragmentManager().beginTransaction().hide(videoFragment).commit();
        }
        getSupportFragmentManager().beginTransaction().show(imageFragment).commit();
      }
    } else {
      headerBarTitle.setText(getResources().getString(R.string.video));
      setHeaderBarCameraBackground(getResources().getDrawable(R.drawable.selector_video_button));
      headerBarCamera.setTag(getResources().getString(R.string.video));

      if (videoFragment != null) {

        if (imageFragment != null) {
          getSupportFragmentManager().beginTransaction().hide(imageFragment).commit();
        }

        getSupportFragmentManager().beginTransaction().show(videoFragment).commit();
        if (videoFragment.getAdapter() != null) {
          videoFragment.getAdapter().notifyDataSetChanged();
        }
      }
    }
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
  }
}
